package io.renren.common.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 企查查调用企业工商模糊搜索接口
 * https://openapi.qcc.com/manage/data/interface
 */
@Component
public class QccUtil {

    private static String key = "95154f4b2ec445c89bb84fa9c519b45b";
    private static String secretKey = "F54BC57410C0FEA492B11F36664998F5";

    public static void main(String[] args) throws Exception {
        //精确到秒的时间戳
        int secondTimestamp = getSecondTimestamp(new Date());
        //token:验证加密值（key+Timespan+SecretKey组成的32位md5加密的大写字符串）
        String token = MD5Util.MD5(key + secondTimestamp + secretKey);
        System.out.println(token);
        //identityCheck("阿里巴巴", token, secondTimestamp + "");
        //getCompanyList("青岛海尔海信信息科技有限公司");
        boolean flag = isCompany("國際科學實踐協會有限公司");
        //boolean flag = isCompany("宁波市海曙区储能学校", "12330203MB1Q01172J");
        System.out.println(flag);
    }

    /**
     * 验证企业是否存在
     * @param keyword
     * @return
     */
    public static boolean isCompany(String keyword){
        List<Map<String, Object>> companyList = getCompanyList(keyword);
        if(companyList!=null) {
            for (Map<String, Object> company : companyList) {
                if (company.get("Name").equals(keyword)) {
                    //(company.get("Status").equals("存续") || company.get("Status").equals("仍注册"))){
                    return true;
                }
            }
        }
        //验证不通过，调用天眼查接口
        return TianyanUtil.isCompany(keyword);
    }

    /**
     * 验证企业和组织机构代码证是否匹配
     * @param keyword
     * @param companyNo
     * @return
     */
    public static boolean isCompany(String keyword, String companyNo){
        List<Map<String, Object>> companyList = getCompanyList(keyword);
        if(companyList!=null){
            for(Map<String, Object> company:companyList){
                if(company.get("Name").equals(keyword) && company.get("CreditCode").equals(companyNo.toUpperCase())){
                    return true;
                }
            }
        }
        System.out.println("企业和组织机构代码证不匹配");
        //验证不通过，调用天眼查接口
        return TianyanUtil.isCompany(keyword, companyNo);
        //return false;
    }

    //获取企业列表
    public static List<Map<String,Object>> getCompanyList(String keyword){
        //精确到秒的时间戳
        int secondTimestamp = getSecondTimestamp(new Date());
        //token:验证加密值（key+Timespan+SecretKey组成的32位md5加密的大写字符串）
        String token = MD5Util.MD5(key + secondTimestamp + secretKey);
        System.out.println(token);
        String result = identityCheck(keyword, token, secondTimestamp + "");
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("Status")==200){
            //JSONArray jsonArray = (JSONArray) jsonObject.get("Result");
            return (List<Map<String, Object>>) jsonObject.get("Result");
        }else{
            System.out.println("调用企查查接口失败");
            System.out.println(jsonObject.get("Message"));
            return null;
        }
    }

    public static String identityCheck(String keyword,String token, String timeStamp) {
        System.out.println("-----------------开始调用--------------->");
        System.out.println("token" + token);
        //String keyword = "阿里巴巴";
        //企业关键字模糊查询
        String url = "https://api.qichacha.com/FuzzySearch/GetList?key=" + key + "&searchKey=" + keyword;
        //企业关键字获取详细信息
        //String url = "http://api.qichacha.com/ECIV4/GetBasicDetailsByName?key=" + key + "&dtype=json" + "&keyword=" + keyword;
        System.out.println("请求url:" + url);
        //boolean match = false; //是否匹配
        String result = "";
        try {
            result = doGet(url, token, timeStamp);
            System.out.println("请求结果：" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("<-----------------调用结束---------------");
        return result;
    }

    /**
     * 带参数的get请求
     *
     * @param url
     * @param token
     * @param timeSpan
     * @param o
     * @return
     */
    public static String doGet(String url, String token, String timeSpan) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            //添加header 头
            httpGet.setHeader("Token", token);
            httpGet.setHeader("Timespan", timeSpan);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 获取精确到秒的时间戳
     *
     * @return
     */
    public static int getSecondTimestamp(Date date) {
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Integer.valueOf(timestamp.substring(0, length - 3));
        } else {
            return 0;
        }
    }

}
